package org.ghub.pdf;

import java.io.IOException;

import com.itextpdf.text.pdf.PdfArray;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfIndirectReference;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

public class pdfExtractor {
	
	private String url;
	private int page=1;
	private String allText="";
			
	public pdfExtractor() {
	}	
	
	public pdfExtractor(String url) {
		this.url = url;
	}
	
	public String generateTree() throws IOException
	{
		this.setAllText("");
		PdfReader reader = new PdfReader(this.getUrl());
		PdfDictionary dictBase = reader.getCatalog();
		PdfDictionary dict = dictBase.getAsDict(PdfName.PAGES);
		this.expand(dict);
		return this.getAllText();
	}
	
	public void expand(PdfDictionary dict) {		 
		
		 if (dict == null)
		 return;
		 PdfIndirectReference ref = dict.getAsIndirectObject(PdfName.PARENT);
		 if (dict.isPage()) {
		 this.setAllText(this.getAllText()+"Child of " + ref + ": PAGE " + (page++)+" \n");
		 }
		 else if (dict.isPages()) {
		 if (ref == null)
			 this.setAllText(this.getAllText()+"PAGES ROOT"+" \n");
		 else
		 System.out.println(this.getAllText()+"Child of " + ref + ": PAGES"+" \n");
		 PdfArray kids = dict.getAsArray(PdfName.KIDS);
		 System.out.println(kids);
		 if (kids != null) {
		 for (int i = 0; i < kids.size(); i++) {
		 this.expand(kids.getAsDict(i));
		 }
		 }
		 }
		 }
	
	public String generateText() throws IOException
	{
		this.setAllText("");
		PdfReader pr=new PdfReader(this.getUrl());		
		for (int i = 1; i < this.getPage(); i++) {
	        String str=PdfTextExtractor.getTextFromPage(pr, i); 
	        this.setAllText(this.getAllText()+str+" \n");
		}
		return this.getAllText();
	}


	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public String getAllText() {
		return allText;
	}
	public void setAllText(String allText) {
		this.allText = allText;
	}	

}
